package com.xqq.juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDebugger {
    public static void main(String[] args) {
        final int THREAD_COUNT = 5;
        CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT, () ->
                System.out.println("\n所有线程已到达屏障点，执行屏障操作\n"));

        for (int i = 1; i <= THREAD_COUNT; i++) {
            new Thread(new Traveler(i, barrier), "Traveler-" + i).start();
        }
    }

    static class Traveler implements Runnable {
        private final int id;
        private final CyclicBarrier barrier;

        public Traveler(int id, CyclicBarrier barrier) {
            this.id = id;
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                System.out.printf("[%tT] Traveler-%d 出发前往集合点\n", System.currentTimeMillis(), id);

                // 模拟前往集合点的时间
                Thread.sleep((long)(Math.random() * 3000));

                System.out.printf("[%tT] Traveler-%d 到达集合点，等待其他人\n", System.currentTimeMillis(), id);

                // 等待其他线程
                int index = barrier.await();

                System.out.printf("[%tT] Traveler-%d 继续旅行 (index=%d)\n", System.currentTimeMillis(), id, index);

            } catch (InterruptedException | BrokenBarrierException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}